package demo;

class MyBlockingQueue{
    private int[] arr=new int[1000];
    private int size=0;
    private int start=0;
    private int end=0;
    private Object locker=new Object();//锁
    public void put(int value) throws InterruptedException {
        synchronized (locker){
            if(size==arr.length){
                locker.wait();
            }
            arr[end]=value;
            end++;
            if(end>=arr.length){
                end=0;
            }
            size++;
            locker.notify();
        }
    }
    public Integer take() throws InterruptedException {
        synchronized (locker){
            if(size==0){
                locker.wait();
            }
            int tmp=arr[start];
            start++;
            if(start>=arr.length){
                start=0;
            }
            size--;
            locker.notify();
            return tmp;
        }
    }
}
public class Demo7 {
    private static MyBlockingQueue blockingQueue=new MyBlockingQueue();
    public static void main(String[] args) {
        Thread t1=new Thread(()->{
            int n=1;
            while (true){
                try {
                    blockingQueue.put(n);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                n++;
            }
        });
        t1.start();
        Thread t2=new Thread(()->{
            while (true){
                try {
                    System.out.println(blockingQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
}
